package com.eshop.modules.wechat.rest;

import org.springframework.web.bind.annotation.PostMapping;
import com.eshop.modules.aop.ForbidSubmit;
import com.alibaba.fastjson.JSONObject;
import cn.hutool.core.util.ObjectUtil;
import com.eshop.modules.mp.domain.WechatReply;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import com.eshop.modules.mp.service.WechatReplyService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;

@Api(tags = { "商城:微信回復管理" })
@RestController
@RequestMapping({ "api" })
public class WechatReplyController
{
    private final WechatReplyService wechatReplyService;
    
    public WechatReplyController(final WechatReplyService wechatReplyService) {
        this.wechatReplyService = wechatReplyService;
    }
    
    @ApiOperation("查询")
    @GetMapping({ "/yxWechatReply" })
    @PreAuthorize("@el.check('admin','YXWECHATREPLY_ALL','YXWECHATREPLY_SELECT')")
    public ResponseEntity getYxWechatReplys() {
        return new ResponseEntity(this.wechatReplyService.isExist("subscribe"), HttpStatus.OK);
    }
    
    @ForbidSubmit
    @ApiOperation("新增自动回复")
    @PostMapping({ "/yxWechatReply" })
    @PreAuthorize("@el.check('admin','YXWECHATREPLY_ALL','YXWECHATREPLY_CREATE')")
    public ResponseEntity create(@RequestBody final String jsonStr) {
        final JSONObject jsonObject = JSON.parseObject(jsonStr);
        final WechatReply wechatReply = new WechatReply();
        final WechatReply isExist = this.wechatReplyService.isExist(jsonObject.get("key").toString());
        wechatReply.setKey(jsonObject.get("key").toString());
        wechatReply.setStatus(Integer.valueOf(jsonObject.get("status").toString()));
        wechatReply.setData(jsonObject.get("data").toString());
        wechatReply.setType(jsonObject.get("type").toString());
        if (ObjectUtil.isNull(isExist)) {
            this.wechatReplyService.create(wechatReply);
        }
        else {
            wechatReply.setId(isExist.getId());
            this.wechatReplyService.upDate(wechatReply);
        }
        return new ResponseEntity(HttpStatus.CREATED);
    }
}
